#if !defined(RESOURCEINSTANCE_H__INCLUDED_)
#define RESOURCEINSTANCE_H__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "SSMutex.h"

class CResourceInstance  
{
public:
	inline static HINSTANCE Get()
	{
		AUTO_MUTEX(CResourceInstance);

		return Instance().m_hInstResource;
	}

	inline static void Reload()
	{
		AUTO_MUTEX(CResourceInstance);

		Instance().LoadResourceLibrary();
	}

public:
	~CResourceInstance()
	{
		AUTO_MUTEX(CResourceInstance);

//		if(m_hInstResource)
//		{
//			::FreeLibrary(m_hInstResource);
//			m_hInstResource = NULL;
//		}
	}

protected:
	inline static CResourceInstance &Instance()
	{
		static CResourceInstance instance;

		return instance;
	}

	CResourceInstance() : m_hInstResource(NULL)
	{
		AUTO_MUTEX(CResourceInstance);

		LoadResourceLibrary();
	}

	CResourceInstance(CResourceInstance &/*rRhs*/) { }
	CResourceInstance &operator = (CResourceInstance &/*rRhs*/) { return *this; }

	inline void LoadResourceLibrary()
	{
		if(m_hInstResource)
		{
			::FreeLibrary(m_hInstResource);
			m_hInstResource = NULL;
		}

		// read LANGID from registry (HKCU\software\ZZzz.oOO\DragIt\LangID)
		regdword rgdwLangID(SECTION _T("LangID"), HKEY_CURRENT_USER);
		LANGID wLangID = (LANGID)(DWORD)rgdwLangID;
		if(0 == wLangID)
			wLangID = GetUserDefaultLangID();
		
		regtstring rgstrPathName(SECTION _T("LangPath"), HKEY_CURRENT_USER);
		std::tostringstream tss;
		tss << (std::tstring)rgstrPathName << _T("\\lc") << std::hex << wLangID;
		
		if( 0 == wLangID || NULL == ( m_hInstResource = ::LoadLibrary( tss.str().c_str() ) ) ) 
		{ 
			// we didn't find the desired language satellite DLL, lets go with English (default).
			std::tostringstream tss;
			tss << (std::tstring)rgstrPathName << _T("\\lc") << std::hex << 0x409;
			
			m_hInstResource = ::LoadLibrary( tss.str().c_str() ); 
		} 
	}

	// reference:
	// http://www.microsoft.com/globaldev/getwr/steps/wrg_mui.mspx
	// http://www.microsoft.com/globaldev/handson/dev/muiapp.mspx
	LANGID GetUserDefaultLangID() const
	{
		OSVERSIONINFO osvi;
		osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		::GetVersionEx(&osvi);

		if( 4 == osvi.dwMajorVersion && 10 >= osvi.dwMinorVersion )
		{
			// Win95, Win98
			regdword rgdwLangID(_T("Control Panel\\Desktop\\ResourceLocale\\"), HKEY_CURRENT_USER);
			return (LANGID)(DWORD)rgdwLangID;
		}
		else if( (4 == osvi.dwMajorVersion && 90 <= osvi.dwMinorVersion) || 5 == osvi.dwMajorVersion )
		{
			// WinMe, Win2K, WinXP
			return ::GetUserDefaultLangID();
		}

		return 0;
	}

private:
	HINSTANCE m_hInstResource;
};

#endif // !defined(RESOURCEINSTANCE_H__INCLUDED_)
